package com.example.equipmentjava.xiaoxinhuan;

/**
 * @author 邓昕劼
 * @version 1.3
 */


import com.alibaba.fastjson.JSON;
import com.example.equipmentjava.xiaoxinhuan.pojo.AlarmEvent;
import com.example.equipmentjava.xiaoxinhuan.pojo.PersonnelInformation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 智能手环项目  同步到启效云
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/TimedH")
public class TimedHController {

    public static final Logger logger = LoggerFactory.getLogger(TimedHController.class);
    /**
     * 长护健康启效云对接接口的AppKey以及appSecret
     **/
    private static final String appKey = "d3aa45bbd1e94d70b5fe59b1fa37da21";
    private static final String appSecret = "883fbc209be344e899544af7c7caa0fc";
    private static final String qxUrl = "https://changhu.qixiaocloud.com";



    /**
     * 接收推送数据到启效 onenet验证
     */    /**
     * onenet推送数据到启效
     */
    @PostMapping("QiXiaoPush")
    @ResponseBody
    public ResponseEntity<String> TimedOne(@RequestBody String body){
        logger.info("-----------------科强推送数据---post方法-----------------------");
        logger.info("body数据="+body);
        net.sf.json.JSONObject qxAddJJson = net.sf.json.JSONObject.fromObject(body);
        net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(qxAddJJson.getString("msg"));
        // 检查msg节点是否包含notifyType字段，以区分第一种数据格式
        if (data.has("notifyType")) {
            logger.info("------------设备信息推送--------------");
            PersonnelInformation personnelInformation = new PersonnelInformation();
            String data2 = data.getString("data");
            String imei = data.getString("deviceName"); //设备名称imei
            personnelInformation.setImie(imei);
            net.sf.json.JSONObject qxAddJJson2 = net.sf.json.JSONObject.fromObject(data2);
            net.sf.json.JSONObject data3 = net.sf.json.JSONObject.fromObject(qxAddJJson2.getString("params"));
            personnelInformation.setBattery(safeGetString(data3, "Battery"));
            personnelInformation.setBirthday(safeGetString(data3, "Birthday"));
            personnelInformation.setBloodPressure(safeGetString(data3, "BloodPressure"));
            personnelInformation.setBodyTemperature(safeGetString(data3, "BodyTemperature"));
            personnelInformation.setDeviceAddress(safeGetString(data3, "DeviceAddress"));
            personnelInformation.setDiastolic(safeGetString(data3, "Diastolic"));
            personnelInformation.setGender(safeGetString(data3, "Gender"));
            personnelInformation.setLivingStyle(safeGetString(data3, "LivingStyle"));
            personnelInformation.setLoginName(safeGetString(data3, "LoginName"));
            personnelInformation.setPositioningData(safeGetString(data3, "Positioningdata"));
            personnelInformation.setShrink(safeGetString(data3, "Shrink"));
            personnelInformation.setSteps(safeGetString(data3, "Steps"));
            personnelInformation.setWear(safeGetString(data3, "Wear"));
            personnelInformation.setWearer(safeGetString(data3, "Wearer"));
            personnelInformation.setWearerPhone(safeGetString(data3, "WearerPhone"));
            personnelInformation.setWearerType(safeGetString(data3, "WearerType"));
            personnelInformation.setHeartRate(safeGetString(data3, "heartRate"));
//            personnelInformation.setImie(safeGetString(data3, "imie"));
            personnelInformation.setLat(safeGetString(data3, "lat"));
            personnelInformation.setLng(safeGetString(data3, "lng"));
            personnelInformation.setLocatemode(safeGetString(data3, "locatemode"));
            personnelInformation.setLocation(safeGetString(data3, "location"));
            personnelInformation.setNumber1(safeGetString(data3, "number1"));
            personnelInformation.setNumber2(safeGetString(data3, "number2"));
            personnelInformation.setNumber3(safeGetString(data3, "number3"));
            personnelInformation.setSleep(safeGetString(data3, "sleep"));
            if(data3.has("Age")){
                String Age = data3.getString("Age");
                net.sf.json.JSONObject AgeJson = net.sf.json.JSONObject.fromObject(Age);
                personnelInformation.setAge(AgeJson.getString("value"));
                personnelInformation.setAgeType(AgeType(AgeJson.getString("value")));
                personnelInformation.setAgeNumeral(Integer.parseInt(AgeJson.getString("value")));
            }
            logger.info("设备imei： " +personnelInformation.getImie()+" 设备信息："+ personnelInformation);
            Withdraw(personnelInformation); // 同步到启效云
            //设备报警信息
            if(data3.has("Alarm")){
                String Alarm = data3.getString("Alarm");
                net.sf.json.JSONObject AlarmJson = net.sf.json.JSONObject.fromObject(Alarm);
                Alarm = AlarmJson.getString("value");
                net.sf.json.JSONObject AlarmJsonList = net.sf.json.JSONObject.fromObject(Alarm);
                AlarmEvent alarmEvent = new AlarmEvent();
                alarmEvent.setAddress(HasString(AlarmJsonList, "Address"));//报警位置
                alarmEvent.setLng(HasString(AlarmJsonList, "lng"));//经度
                alarmEvent.setNotificationType(HasString(AlarmJsonList, "NotificationType"));//报警内容
                alarmEvent.setLocatemode(HasString(AlarmJsonList, "locatemode"));//定位方式
                alarmEvent.setPositioningdata(HasString(AlarmJsonList, "Positioningdata"));//定位数据
                alarmEvent.setLat(HasString(AlarmJsonList, "lat"));//经度
                alarmEvent.setCreated(HasString(AlarmJsonList, "Created"));//报警时间
                alarmEvent.setImei(personnelInformation.getImie());//imei
                Alarm(alarmEvent);// 设备报警信息同步到启效云
                logger.info("设备imei： " +personnelInformation.getImie()+ " 报警信息 = " + Alarm);
            }
        }
        if (data.has("dev_name")) {
            logger.info("------------设备在线状态--------------");
            String dev_name = data.getString("dev_name"); //设备名称imei
            String at = data.getString("at"); //设备上报的时间戳
            String pid = data.getString("pid");//产品id
            String type = data.getString("type"); //固定值：2
            String status = data.getString("status");//设备状态，1:在线；0:离线
            logger.info("设备imei："+dev_name+"设备状态："+wear(status));
            PersonnelInformation personnelInformation = new PersonnelInformation();
            personnelInformation.setImie(dev_name);
//            personnelInformation.setWear(wear(status));
            Withdraw(personnelInformation); // 同步到启效云
        }
        return ResponseEntity.ok("200");
    }
    @GetMapping("QiXiaoPush")
    @ResponseBody
    public ResponseEntity<String> TimedOne(HttpServletRequest body){
        String msg = body.getParameter("msg");
        String nonce = body.getParameter("nonce");
        String signature = body.getParameter("signature");
        logger.info("科强url验证---get方法");
        return ResponseEntity.ok(msg);
    }

    //Age数据处理
    public String AgeType(String age) {
        String type = "";
        int ageType = Integer.parseInt(age);
        if (ageType<60){
            type = "60岁以下";
        }
        if (ageType>=60 && ageType<=70){
            type = "60-70岁";
        }
        if (ageType>=70 && ageType<=80){
            type = "70-80岁";
        }
        if (ageType>80){
            type = "80岁以上";
        }
        return type;
    }


    public void Alarm(AlarmEvent alarmEvent) {
        try {
            String qxToken = token();
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            String url = "https://apaas.qixiaocloud.com/open/qx-apaas-lowcode/ZNSH/insertAlarm";
            headMap.put("Authorization", qxToken);
            param = new HashMap();
            param.put("Imie", alarmEvent.getImei());
            param.put("Address", alarmEvent.getAddress());
            param.put("lng", alarmEvent.getLng());
            param.put("NotificationType", alarmEvent.getNotificationType());
            param.put("locatemode", alarmEvent.getLocatemode());
            param.put("Positioningdata", alarmEvent.getPositioningdata());
            param.put("lat", alarmEvent.getLat());
            param.put("Created", alarmEvent.getCreated());
            String qxAdd = postJsonParam(url, param, headMap);
            logger.info("qxAdd = " + qxAdd);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("报错 = " + e);
        }
    }




    private String HasString(net.sf.json.JSONObject data, String key) {
        if(data.has(key)){
            return data.getString(key);
        }else{
            return null;
        }

    }


    private String safeGetString(net.sf.json.JSONObject data, String key) {
        if(data.has(key)){
            String string = data.getString(key);
            net.sf.json.JSONObject qxAddJJson2 = net.sf.json.JSONObject.fromObject(string);
            string = qxAddJJson2.getString("value");
            return string;
        }else{
            return null;
        }

    }


    //提取查询的信息PersonnelInformation
    public void Withdraw(PersonnelInformation personnelInformation) {
        try {
            String qxToken = token();
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            String url = "https://apaas.qixiaocloud.com/open/qx-apaas-lowcode/ZNSH/InsertRYXX";
            headMap.put("Authorization", qxToken);
            param = new HashMap();
            param.put("Age", personnelInformation.getAge());
            param.put("Battery", personnelInformation.getBattery());
            param.put("Birthday", personnelInformation.getBirthday());
            param.put("BloodPressure", personnelInformation.getBloodPressure());
            param.put("BodyTemperature", personnelInformation.getBodyTemperature());
            param.put("DeviceAddress", personnelInformation.getDeviceAddress());
            param.put("Diastolic", personnelInformation.getDiastolic());
            param.put("Gender", personnelInformation.getGender());
            param.put("LivingStyle", personnelInformation.getLivingStyle());
            param.put("LoginName", personnelInformation.getLoginName());
            param.put("PositioningData", personnelInformation.getPositioningData());
            param.put("Shrink", personnelInformation.getShrink());
            param.put("Steps", personnelInformation.getSteps());
            param.put("Wear", personnelInformation.getWear());
            param.put("Wearer", personnelInformation.getWearer());
            param.put("WearerPhone", personnelInformation.getWearerPhone());
            param.put("WearerType", personnelInformation.getWearerType());
            param.put("HeartRate", personnelInformation.getHeartRate());
            param.put("Imie", personnelInformation.getImie());
            param.put("Lat", personnelInformation.getLat());
            param.put("Lng", personnelInformation.getLng());
            param.put("Locatemode", personnelInformation.getLocatemode());
            param.put("Location", personnelInformation.getLocation());
            param.put("Number1", personnelInformation.getNumber1());
            param.put("Number2", personnelInformation.getNumber2());
            param.put("Number3", personnelInformation.getNumber3());
            param.put("Sleep", personnelInformation.getSleep());
            param.put("AgeType", personnelInformation.getAgeType());
            param.put("AgeNumeral", personnelInformation.getAgeNumeral());
            String qxAdd = postJsonParam(url, param, headMap);
            logger.info("qxAdd = " + qxAdd);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("报错 = " + e);
        }
    }



    //wear数据处理
    public String wear(String wear) {
        if (wear.equals("1")) {
            wear = "在线";
        }
        if (wear.equals("0")) {
            wear = "离线";
        }
        return wear;
    }



    //去除引号括号
    public List<String> remove(List<String> list) {
        List<String> imeiDataList = list.stream().map((resp) -> {
            // 删除双引号和方括号
            String result1 = resp.replace("\"", "").replace("[", "").replace("]", "");
            return result1;
        }).collect(Collectors.toList());
        return imeiDataList;
    }


    /**
     * 生成token
     */
    public static String token() {
        try {
            String url = qxUrl + "/open/oauth/token";
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            param.put("appKey", appKey);
            param.put("appSecret", appSecret);
            String qxLogin = null;
            qxLogin = postJsonParam(url, param, headMap);
            net.sf.json.JSONObject qxLoginJson = net.sf.json.JSONObject.fromObject(qxLogin);
//            logger.info("token获取：" + qxLogin);
            String success = qxLoginJson.getString("success");
            if ("true".equals(success)) {
                net.sf.json.JSONObject qxData = net.sf.json.JSONObject.fromObject(qxLoginJson.getString("data"));
                String qxToken = qxData.getString("access_token");
                //将token存到redis设置全局有效时间 10分钟
//                System.out.println("token = " + stringRedisTemplate);
                return qxToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     *  将map数据转成json数据
     */
    public static String postJsonParam(String url, Map<String, String> param, Map<String, String> headMap) throws Exception {
        String jsonparam = mapToJSON(param);
//        logger.info("请求参数串：" +jsonparam);
//        System.out.println("jsonparam = " + jsonparam);
        return doPost(url, jsonparam, headMap);
    }

    /**
     * map 转 json
     *
     * @param param
     * @return
     */
    public static String mapToJSON(Map param) {
        String json = JSON.toJSONString(param);
        return json;
    }

    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @param headMap
     * @return
     */
    public static String doPost(String url, String params, Map<String, String> headMap) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        //如果headMap不为空，则需要添加接口鉴权字段
        if (headMap != null) {
            Iterator it = headMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                httpPost.setHeader(key, headMap.get(key));
            }
        }
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
                return jsonString;
            } else {
                System.out.println("!!!!!!!!responseEntity:" + EntityUtils.toString(response.getEntity(), "UTF-8"));
                return "请求失败，服务器状态码：" + state;
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
